<script setup lang="ts">
  // 声明登录表单
  import { loginAPI } from '@/api'
  import { PAGE_PATH } from '@/constants'
  import { useTokenStore } from '@/store/token'
  import type { LoginParams } from '@/types/user'
  import { ref } from 'vue'
  const loginForm = ref<LoginParams>({
    mobile: '13230000001',
    password: 'abc12345',
  })
  const formRef = ref()
  defineOptions({
    options: {
      styleIsolation: 'shared',
    },
  })

  const loginRules = {
    mobile: {
      rules: [
        {
          required: true,
          errorMessage: '请输入手机号',
        },
        {
          pattern: /^1[3-9]\d{9}$/,
          errorMessage: '手机号格式不正确',
        },
      ],
    },
    code: {
      rules: [
        {
          required: true,
          errorMessage: '请输入密码',
        },
        {
          pattern: /^\d{8}$/,
          errorMessage: '密码不正确',
        },
      ],
    },
  }
  const agree = ref(false)

  const changeValue = () => {
    agree.value = !agree.value
  }
  const login = async () => {
    await formRef.value.validate()
    if (!agree.value) {
      uni.showToast({ title: '您未勾选用户平台协议', icon: 'none' })
      return
    }
    formRef.value.validate()
    const res = await loginAPI(loginForm.value)
    // token存入pinia
    const tokenStore = useTokenStore()
    tokenStore.setToken(res.token) // 写入token
    uni.switchTab({
      url: PAGE_PATH.HOME_PAGE,
    }) // // 返回上一个页面
  }
</script>
<template>
  <uni-forms class="login-form" ref="formRef" :rules="loginRules" :modelValue="loginForm">
    <uni-forms-item name="mobile">
      <uni-easyinput
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        v-model="loginForm.mobile"
        placeholder-style="color: #C3C3C5"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <uni-easyinput
        type="password"
        placeholder="请输入密码"
        :input-border="false"
        v-model="loginForm.password"
        placeholder-style="color: #C3C3C5"
      />
    </uni-forms-item>
    <view class="agreement">
      <radio :checked="agree" @click="changeValue" color="#16C2A3" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="login">登 录</button>
    <navigator hover-class="none" class="uni-navigator" url=" "> 忘记密码？ </navigator>
  </uni-forms>
</template>
<style lang="scss">
  @import './styles.scss';
</style>
